package com.invest.tool.server.service.impl;

import com.invest.tool.server.bean.request.CompareBeanRequest;
import com.invest.tool.server.bean.response.CompareBeanResponse;
import com.invest.tool.server.config.ConfigProperties;
import com.invest.tool.server.service.LiXingRenService;
import com.invest.tool.server.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class LiXingRenServiceImpl implements LiXingRenService {

    @Autowired
    private ConfigProperties configProperties;

    @Autowired
    private RestTemplate restTemplate;

    private String jwt;

    @Override
    public String login() {
        String username = configProperties.getUsername();
        String password = configProperties.getPassword();
        Map<String, String> request = new HashMap<>();
        request.put("accountName", username);
        request.put("password", password);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36");
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(request, headers);
        ResponseEntity<Map> result = restTemplate.exchange(configProperties.getLoginUrl(),
                HttpMethod.POST,
                requestEntity,
                Map.class);
        String cookie = result.getHeaders().get("Set-Cookie").get(0);
        String[] cookieAttrs = cookie.split(";");
        for (String attr : cookieAttrs) {
            String[] keyValue = attr.split("=");
            if ("jwt".equals(keyValue[0])) {
                jwt = keyValue[1];
                break;
            }
        }
        return jwt;
    }

    @Override
    public CompareBeanResponse compareInfo(CompareBeanRequest compareBeanRequest) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36");
        headers.set("cookie", "jwt=" + jwt);
        HttpEntity<CompareBeanRequest> requestEntity = new HttpEntity<>(compareBeanRequest, headers);

        ResponseEntity<CompareBeanResponse> result = restTemplate.exchange(configProperties.getCompareUrl(),
                HttpMethod.POST,
                requestEntity,
                CompareBeanResponse.class);
        CompareBeanResponse response = result.getBody();
        return response;
    }
}
